package com.studynotes.dev.tech.common.utils;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.PrimitiveArrayUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;

import javax.servlet.ServletInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Liu XiaoJun
 * @description: Json工具类
 * @date 2025-11-07 13:27:21
 */
public class JsonUtil {

    private JsonUtil() {

    }

    /**
     * Bean对象转JSON
     *
     * @param object object
     * @param dataFormatString data format string
     * @return json string
     */
    public static String beanToJson(Object object, String dataFormatString) {
        if (object != null) {
            if (CharSequenceUtil.isEmpty(dataFormatString)) {
                return JSONUtil.toJsonStr(object);
            }
            JSONConfig jsonConfig = JSONConfig.create();
            jsonConfig.setDateFormat(dataFormatString);
            return JSONUtil.toJsonStr(object, jsonConfig);
        } else {
            return null;
        }
    }

    /**
     * Bean对象转JSON
     *
     * @param object object
     * @return json string
     */
    public static String beanToJson(Object object) {
        if (object != null) {
            return JSONUtil.toJsonStr(object);
        } else {
            return null;
        }
    }

    private static ObjectMapper objectMapper;

    static {
        objectMapper = SpringUtil.getBean(ObjectMapper.class);
    }

    /**
     * 初始化 objectMapper 属性
     * 通过这样的方式，使用 Spring 创建的 ObjectMapper Bean
     *
     * @param objectMapper ObjectMapper 对象
     */
    public static void init(ObjectMapper objectMapper) {
        JsonUtil.objectMapper = objectMapper;
    }

    @SneakyThrows
    public static String toJsonString(Object object) {
        return objectMapper.writeValueAsString(object);
    }

    @SneakyThrows
    public static String toJsonPrettyString(Object object) {
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
    }

    @SneakyThrows
    public static byte[] toJsonByte(Object object) {
        return objectMapper.writeValueAsBytes(object);
    }


    public static <T> T parseObject(String text, Class<T> clazz) {
        if (CharSequenceUtil.isEmpty(text)) {
            return null;
        }
        try {
            return objectMapper.readValue(text, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static JSONObject parseJsonObject(String text) {
        return new JSONObject(text);
    }

    /**
     * 将字符串解析成指定类型的对象
     * 使用 {@link #parseObject(String, Class)} 时，在@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) 的场景下，
     * 如果 text 没有 class 属性，则会报错。此时，使用这个方法，可以解决。
     *
     * @param <T> class type
     * @param text 字符串
     * @param clazz 类型
     * @return 对象
     */
    public static <T> T parseObject2(String text, Class<T> clazz) {
        if (CharSequenceUtil.isEmpty(text)) {
            return null;
        }
        return JSONUtil.toBean(text, clazz);
    }

    public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
        if (PrimitiveArrayUtil.isEmpty(bytes)) {
            return null;
        }
        try {
            return objectMapper.readValue(bytes, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(text, typeReference);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> parseArray(String text, Class<T> clazz) {
        if (CharSequenceUtil.isEmpty(text)) {
            return new ArrayList<>();
        }
        try {
            return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static JSONArray parseJsonArray(String text) {
        return new JSONArray(text);
    }


    public static JsonNode parseTree(String text) {
        try {
            return objectMapper.readTree(text);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static JsonNode parseTree(byte[] text) {
        try {
            return objectMapper.readTree(text);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 将json字符串转换成对象
     *
     * @param json json string
     * @param clazz class
     * @param <T> class
     * @return Object
     */
    public static <T> T jsonToBean(String json,  Class<T>  clazz) {
        if (CharSequenceUtil.isEmpty(json) || clazz == null) {
            return null;
        }
        return JSONUtil.toBean(json, clazz);
    }

    /**
     * json字符串转map
     *
     * @param json json string
     * @return Map
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> jsonToMap(String json) {
        if (CharSequenceUtil.isEmpty(json)) {
            return null;
        }
        return JSONUtil.parseObj(json);
    }

    /**
     * 格式化字符串
     *
     * @param formatted formatted string
     * @param bean bean
     * @return formatted string
     */
    public static String format(String formatted, Object bean) {
        return CharSequenceUtil.format(formatted, JSONUtil.toJsonStr(bean));
    }

    /**
     * 将输入流转换为对象
     *
     * @param inputStream inputStream
     * @param clazz class
     * @param <T> class
     * @return Object
     * @throws IOException IOException
     */
    public static <T> T parseInputStream(ServletInputStream inputStream, Class<T> clazz) throws IOException {
        return objectMapper.readValue(inputStream, clazz);
    }
}
